package com.csw.shuanfa.utils.id;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.csw.shuanfa.GlobalConfig.format.DateTimeEntity;
import com.csw.shuanfa.GlobalConfig.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("TestLongController")
public class TestLongController {
    @Autowired
    private SnowFlakeIdUtil idWorker;

    @GetMapping("aa")
    public Result<LocalDateTime> aa(@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime date) {
        long l = 1;
        System.out.printf(l + "");
        String string = JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat).toString();

        SerializeConfig serializeConfig = new SerializeConfig();
        serializeConfig.put(LocalDateTime.class, new LocalDateTimeSerializer());
        String json = JSON.toJSONString(date, serializeConfig);
        System.out.println(json);
        return Result.ok(date);

    }

    @GetMapping("bb")
    public Result<DateTimeEntity> bb(@RequestBody DateTimeEntity date) {
        long l = 1;
        System.out.printf(l + "");
        String string = JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat).toString();

        SerializeConfig serializeConfig = new SerializeConfig();
        serializeConfig.put(LocalDateTime.class, new LocalDateTimeSerializer());
        String json = JSON.toJSONString(date, serializeConfig);
        System.out.println(json);
        return Result.ok(date);

    }

    private static class LocalDateTimeSerializer implements ObjectSerializer {
        private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        @Override
        public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) {
            LocalDateTime dateTime = (LocalDateTime) object;
            String formattedDateTime = dateTime.format(formatter);
            serializer.write(formattedDateTime);
        }
    }


}
